type point = record
  x,y:double;
end;
function Intersection(ax1,ay1,ax2,ay2,bx1,by1,bx2,by2:double):boolean;
var v1,v2,v3,v4:real;
begin
v1:=(bx2-bx1)*(ay1-by1)-(by2-by1)*(ax1-bx1);
v2:=(bx2-bx1)*(ay2-by1)-(by2-by1)*(ax2-bx1);
v3:=(ax2-ax1)*(by1-ay1)-(ay2-ay1)*(bx1-ax1);
v4:=(ax2-ax1)*(by2-ay1)-(ay2-ay1)*(bx2-ax1);
result:=(v1*v2<0) and (v3*v4<0);
end;
function PointOnLine(x1,y1,x2,y2,x,y:double):boolean;
begin
result:=(sqrt(sqr(x2-x1)+sqr(y2-y1)))=(sqrt(sqr(x-x1)+sqr(y-y1))+sqrt(sqr(x-x2)+sqr(y-y2)));
end;
{ At first call INTERSECTION; if FALSE then call pointonline with every point}
function dist(a1,a2,b1,b2:point):point;
var d,da,db,ta,tb: real;
begin
d:=(a1.x-a2.x)*(b2.y-b1.y)-(a1.y-a2.y)*(b2.x-b1.x);
da:=(a1.x-b1.x)*(b2.y-b1.y) - (a1.y-b1.y)*(b2.x-b1.x);
db:=(a1.x-a2.x)*(a1.y-b1.y) - (a1.y-a2.y)*(a1.x-b1.x);
ta:=da/d;
tb:=db/d;
if (0<=ta) and (ta<=1) and (0<=tb) and (tb<=1) then begin
  result.x:=a1.x+ta*(a2.x-a1.x);
  result.y:=a1.y+ta*(a2.y-a1.y);
end else {SEGMENTS DO NOT INTERSECT};
end;